const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');

// 获取代码行数的路由
router.get('/get-code-lines', (req, res) => {
    const projectPath = path.join(__dirname, '..'); // 项目根目录
    let totalLines = 0;

    function countLinesInFile(filePath) {
        try {
            const content = fs.readFileSync(filePath, 'utf8');
            const lines = content.split('\n');
            totalLines += lines.length;
        } catch (err) {
            console.error(`读取文件 ${filePath} 失败:`, err);
        }
    }

    function countLinesInDirectory(dir, recursive = true) {
        try {
            const files = fs.readdirSync(dir);
            files.forEach(file => {
                const filePath = path.join(dir, file);
                const stat = fs.statSync(filePath);
                
                if (stat.isDirectory()) {
                    // 如果是目录且需要递归处理，则继续遍历
                    if (recursive) {
                        countLinesInDirectory(filePath, recursive);
                    }
                } else {
                    // 检查文件扩展名是否为代码文件
                    const ext = path.extname(file).toLowerCase();
                    if (ext === '.js' || ext === '.html' || ext === '.css') {
                        countLinesInFile(filePath);
                    }
                }
            });
        } catch (err) {
            console.error(`访问目录 ${dir} 失败:`, err);
        }
    }

    // 1. 统计根目录下public文件夹内所有文件
    const publicPath = path.join(projectPath, 'public');
    if (fs.existsSync(publicPath)) {
        countLinesInDirectory(publicPath);
    }

    // 2. 统计根目录下routes文件夹内所有文件
    const routesPath = path.join(projectPath, 'routes');
    if (fs.existsSync(routesPath)) {
        countLinesInDirectory(routesPath);
    }

    // 3. 统计根目录下的所有代码文件（不包括子目录）
    const rootFiles = fs.readdirSync(projectPath);
    rootFiles.forEach(file => {
        const filePath = path.join(projectPath, file);
        const stat = fs.statSync(filePath);
        
        // 只处理文件，不处理目录
        if (stat.isFile()) {
            const ext = path.extname(file).toLowerCase();
            if (ext === '.js' || ext === '.html' || ext === '.css') {
                countLinesInFile(filePath);
            }
        }
    });

    res.json({ codeLines: totalLines });
});

module.exports = router;